/**
 * 自定义渠道设置
 * */
import React from 'react';
import { Modal, Input, Form, message } from 'antd';
import FileUpload from '@/components/Custom/FileUpload';
import { transformFileList } from '../../../utils';
import { addCustomChannel, updateCustomChannel } from '../../service';

const formItemLayout = {
    labelCol: {
        sm: { span: 7 }
    },
    wrapperCol: {
        sm: { span: 14 }
    }
};
const noop = () => {};
const CustomChannelModal = ({ form, channelType, data, onSuccess, renderTrigger = noop }) => {
    const { getFieldDecorator } = form;
    const [visible, setVisible] = React.useState(false);
    const [submitLoading, setSubmitLoading] = React.useState(false);
    const [readyFlag, setReadyFlag] = React.useState(false);

    // 确定
    const handleOk = () => {
        form.validateFields((err, values) => {
            // console.log('handleOk -> values', values);
            if (!err) {
                const { resourceRelation, ...rest } = values;
                const params = {
                    ...rest,
                    channelType,
                    resourceRelation: resourceRelation?.uploadResourceFile ? [resourceRelation?.uploadResourceFile] : []
                };
                // console.log('handleOk -> params', params);
                setSubmitLoading(true);
                if (data) {
                    updateCustomChannel({
                        ...params,
                        channelId: data.id
                    })
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                message.success('操作成功');
                                if (onSuccess) {
                                    onSuccess();
                                }
                                setVisible(false);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                } else {
                    addCustomChannel(params)
                        .then(res => {
                            const { code, msg } = res;
                            if (code === 10000) {
                                message.success('操作成功');
                                if (onSuccess) {
                                    onSuccess();
                                }
                                setVisible(false);
                            } else {
                                message.error(msg);
                            }
                        })
                        .finally(() => {
                            setSubmitLoading(false);
                        });
                }
            }
        });
    };

    React.useEffect(() => {
        if (!data || !visible) {
            return;
        }
        const { recruitChannelLogoFile = [], channelName } = data;
        const finalFieldsValue = {
            channelName,
            resourceRelation: transformFileList(recruitChannelLogoFile || [])
        };
        // console.log('CustomChannelModal -> finalFieldsValue', finalFieldsValue);
        if (!readyFlag) {
            setReadyFlag(true);
        } else {
            form.setFieldsValue(finalFieldsValue);
        }
    }, [data, visible, readyFlag]);

    // 取消
    const handleCancel = () => {
        setVisible(false);
    };

    // 显示modal
    const handleModal = () => {
        setVisible(true);
    };

    const handleAfterClose = () => {
        form.resetFields();
    };

    return (
        <>
            {renderTrigger({ onClick: handleModal })}
            <Modal
                title={data ? '编辑渠道' : '新增渠道'}
                visible={visible}
                onOk={handleOk}
                onCancel={handleCancel}
                width={640}
                confirmLoading={submitLoading}
                afterClose={handleAfterClose}
            >
                <Form {...formItemLayout} labelAlign="right" style={{ paddingTop: '30px' }}>
                    <Form.Item label="渠道名称">
                        {getFieldDecorator('channelName', {
                            rules: [{ required: true, whitespace: true, message: '请输入渠道名称' }]
                        })(<Input placeholder="请输入渠道名称" maxLength={50} />)}
                    </Form.Item>
                    <Form.Item label="渠道logo" style={{ marginBottom: 0 }}>
                        <div style={{ height: 102 }}>
                            {getFieldDecorator('resourceRelation')(
                                <FileUpload
                                    isSingle
                                    checkFileSize={1}
                                    checkFileSizeMsg="文件大小不能超过1MB！"
                                    categoryCode="recruitChannelLogoFile"
                                    checkFileType="JPG,JPEG,BMP,PNG"
                                    checkFileTypeMsg="只能上传JPG,JPEG,BMP,PNG格式的文件！"
                                />
                            )}
                        </div>
                        <span>支持JPG,JPEG,BMP,PNG格式，大小不可超过1M</span>
                    </Form.Item>
                </Form>
            </Modal>
        </>
    );
};

export default Form.create()(CustomChannelModal);
